/*
 * File Name：PayMoneyActivity.java
 * Copyright：Copyright 2008-2013 CiWong.Inc. All Rights Reserved.
 * Description： PayMoneyActivity.java
 * Modify By：RES-KUNZHU
 * Modify Date：2013-4-18
 * Modify Type：Add
 */
package com.ciwong.mobilelib.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebChromeClient.CustomViewCallback;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.R;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.utils.BaseJumpManager;
import com.ciwong.mobilelib.widget.CWDialog;

import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 浏览器
 *
 * @author RES-KUNZHU
 * @version ciwong v.1.0 2013-4-18
 * @since ciwong v.1.0
 */
public class BrowserActivity extends BaseActivity implements View.OnClickListener {
    protected WebView mWebView;

    private static ProgressBar mProgress;

    /**
     * 传过来的网址
     */
    private String mReceiveWebPath = "";

    /**
     * 被处理的url
     */
    private String mHandlerWebUrl = "";

    public int jumpType;

    /**
     * 传过来的标题
     */
    private String mFirstTitle = "";

    private ViewGroup mVideoContainer;

    private CustomViewCallback myCallback = null;

    private boolean mPageIsFinish = false;

    private HashMap<String, String> mTitleMap = new HashMap<String, String>();// 存放url和上一个界面的标题

    private boolean isLoadWebTitle = true;

    private String mUrl = "http://cdn2.down.apk.gfssan.com/asdf/Pfiles" + "/2013/8/1/45021_cbb0786e-14d0-4715-8b56-34a0ce91d94e.apk";

    private Handler mBackHandler = new Handler();

    private static int mNewProgress = 0;

    private LongTask longtask;

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.btn_try_again) {//重试
            if (NetworkUtils.isOnline()) {
                rel_no_net_work.setVisibility(View.GONE);
                rel_pay_container.setVisibility(View.GONE);
                mWebView.loadUrl(mHandlerWebUrl);
            }
        }
    }

//    protected TitleBar browser_title_bar;

    public interface LoadCallback {
        void onLoadOver();// 加载完成回调

        void onBackFinish();// 返回监听
    }

    protected LoadCallback loadCallback, backCallback;

    protected void setLoadCallback(LoadCallback loadCallback) {
        this.loadCallback = loadCallback;
    }

    protected void setBackCallback(LoadCallback backCallback) {
        this.backCallback = backCallback;
    }

    private ValueCallback mUploadMessage;

    private final static int FILECHOOSER_RESULTCODE = 1;// 文件选择回调

    private WebChromeClient wcc = new WebChromeClient() {
        public View getVideoLoadingProgressView() {
            return new ProgressBar(BrowserActivity.this);
        }

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            if (myCallback != null) {
                myCallback.onCustomViewHidden();
                myCallback = null;
                return;
            }
            mVideoContainer.setVisibility(View.VISIBLE);
            mVideoContainer.addView(view);
            myCallback = callback;
        }

        @Override
        public void onHideCustomView() {
            if (mVideoContainer.getChildCount() >= 1) {
                if (myCallback != null) {
                    myCallback.onCustomViewHidden();
                    myCallback = null;
                }
                mVideoContainer.removeAllViews();
                mVideoContainer.setVisibility(View.GONE);
            }
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            System.out.println("原始网页Title：onReceivedTitle  "+title);
            if (! webpageException(title)){
                rel_pay_container.setVisibility(View.GONE);
                rel_no_net_work.setVisibility(View.VISIBLE);
            }else{
                rel_pay_container.setVisibility(View.VISIBLE);
                rel_no_net_work.setVisibility(View.GONE);
            }
            if (!isLoadWebTitle) {
                return;
            }
            if (null != mWebView && !mWebView.canGoBack()) // 加载首页
            {
                title = TextUtils.isEmpty(mFirstTitle) ? title : mFirstTitle;// 首页使用intent传递过来的标题，只有当传递过来的标题为空时，才使用网页标题
                setTitle(title);
            } else {
                mTitleMap.put(view.getUrl(), getTitleText());
            }
            setTitleText(title);
//            super.onReceivedTitle(view, title);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress < 60) {

            }

            if (longtask != null) {
                longtask.cancel(true);
            }
            if (mProgress != null && newProgress < mNewProgress) {
                mProgress.setProgress(0);
            }
            longtask = new LongTask();
            mNewProgress = newProgress;
            longtask.execute();
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message,
                                 final JsResult result) {
            CWLog.d("debug", "a2：" + message);
            jsAlert(view, url, message, result);
            return true;
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message,
                                   final JsResult result) {
            jsConfirm(view, url, message, result);
            return true;
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message,
                                  String defaultValue, final JsPromptResult result) {
            jsPrompt(view, url, message, defaultValue, result);
            return true;
        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback uploadMsg) {
            openFileChooser(uploadMsg, null, null);
        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            mUploadMessage = uploadMsg;
            BaseJumpManager.jumpToSysChooseFile(BrowserActivity.this,
                    FILECHOOSER_RESULTCODE, false);
        }

        // For Android 4.1
        public void openFileChooser(ValueCallback uploadMsg, String acceptType,
                                    String capture) {
            mUploadMessage = uploadMsg;
            BaseJumpManager.jumpToSysChooseFile(BrowserActivity.this,
                    FILECHOOSER_RESULTCODE, true);
        }

    };
    /**
     * 通过标题判断网页是否异常
     *
     * @param title 标题
     * @return true 表示网页正常情况，false表示网页异常
     */
    private boolean webpageException(String title) {
        if (title == null) return true;
        if (title.contains("网页")) {
            if (title.contains("找不到") || title.contains("无法打开")
                    || title.contains("错误") || title.contains("异常"))
                return false;
        }
        return true;
    }
    @Override
    public void onDestroy() {
        try {
            super.onDestroy();
            if (mBackHandler != null) {
                mBackHandler.removeCallbacksAndMessages(null);
            }
            if (mProgress != null) {
                mProgress.clearAnimation();
                mProgress = null;
            }
            if (mWebView != null) {
                try {
                    mWebView.destroyDrawingCache();
                    mWebView.clearCache(true);
                    rel_pay_container.removeView(mWebView);
                    mWebView.removeAllViews();
                    mWebView.clearHistory();
                    mWebView.destroy();
                    mWebView = null;
                } catch (Exception e) {
                }
            }
            if (longtask != null) {
                longtask.cancel(true);
                longtask = null;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转类型
     */
    public class BrowerJumpType {
        /**
         * 时文网页展示
         */
        public static final int TYPE_ASSEY = 1;

        /**
         * 听说模考答案查看网页
         */
        public static final int TYPE_LS_ANSWWER = 2;

    }

    /**
     * 是否需要禁止返回操作
     *
     * @return
     */
    public boolean isNeedBanBack() {
        return backCallback == null && Build.VERSION.SDK_INT == 19
                && jumpType == BrowerJumpType.TYPE_LS_ANSWWER
                && mNewProgress <= 90;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 解决4.4系统快速返回进入界面出现空白的问题
            if (isNeedBanBack()) {
                CWLog.d("banBack", "禁止返回");
                return true;
            }

            if (mVideoContainer.getVisibility() == View.VISIBLE) {
                wcc.onHideCustomView();
            } else {

                if (mWebView.canGoBack()) {
                    isLoadWebTitle = false;
                    // System.out.println(mWebView.getTitle());
                    String currentUrl = mWebView.getUrl();
                    if (mTitleMap.isEmpty()
                            || TextUtils.isEmpty(mTitleMap.get(currentUrl))) {
                        setTitleText(mFirstTitle);
                    } else {
                        setTitleText(mTitleMap.get(currentUrl));
                        mTitleMap.remove(currentUrl);
                    }
                    mWebView.goBack();
                } else {
                    if (backCallback != null) {
                        backCallback.onBackFinish();
                    } else {
                        finish();
                    }
                }
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);

    }

    @Override
    public void onPause() {
        try {
            super.onPause();
            mWebView.onPause();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int setView() {
        return R.layout.activity_browser;
    }

    /**
     * 无网络界面
     */
    private RelativeLayout rel_no_net_work;
    /**
     * 正常页面
     */
    private RelativeLayout rel_pay_container;
    /**
     * 无网络重试
     */
    private Button btn_try_again;

    @Override
    public void findViews() {
        showTitleBar();
        mVideoContainer = (ViewGroup) findViewById(R.id.video_container);
        mWebView = (WebView) findViewById(R.id.pay_webview);

        mProgress = (ProgressBar) findViewById(R.id.pay_pro);

        rel_pay_container = (RelativeLayout) findViewById(R.id.rel_pay_container);
        rel_no_net_work = (RelativeLayout) findViewById(R.id.rel_no_net_work);

        btn_try_again = (Button) findViewById(R.id.btn_try_again);
//        browser_title_bar = (TitleBar) findViewById(R.id.browser_title_bar);
    }

    @Override
    public void initEvent() {
        btn_try_again.setOnClickListener(this);
        mWebView.getSettings().setSavePassword(false);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings()
                .setUserAgentString(mWebView.getSettings().getUserAgentString() + ";im-xixin-mobile");
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setPluginState(PluginState.ON);
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                isLoadWebTitle = true;
                if (url != null) {
                    String reg = "((.apk)|(.exe)|(.word)|(.ppt)|(.xls))$";
                    Pattern pat = Pattern.compile(reg);
                    Matcher mat = pat.matcher(url);
                    if (mat.find()) {
                        Uri uri = Uri.parse(url);
                        BaseJumpManager.jumpToSysBrowser(BrowserActivity.this,
                                uri);
                        return true;
                    }
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                view.getSettings().setBlockNetworkImage(false);

                BrowserActivity.this.showRightBtn();
                //原来的代码为什么要展示又隐藏右键
//                BrowserActivity.this.hideRightBtn();
                super.onPageFinished(view, url);
                if (loadCallback != null && !mPageIsFinish) {
                    loadCallback.onLoadOver();
                }
                mPageIsFinish = true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                isLoadWebTitle = true;
                // 如果url中包含.swf表示这个网页有flash
                if (url.contains(".swf")) {
                    // 那么判断手机是否安装flash插件

                    if (!isInstalledFlash()) {
                        uninstallFlash();
                        return;
                    }
                }
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onReceivedSslError(WebView view,
                                           SslErrorHandler handler, android.net.http.SslError error) {
                handler.proceed();
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    System.out.println("原始网页：onReceivedError  "+request.getUrl());
                }
                rel_pay_container.setVisibility(View.GONE);
                rel_no_net_work.setVisibility(View.VISIBLE);
            }

        });
        mWebView.setWebChromeClient(wcc);
    }

    @Override
    public void onResume() {
        super.onResume();
        mWebView.onResume();

    }

    @Override
    public void init() {

        setGoBackListener(new GoBackListener() {
            @Override
            public void goBack() {
                if (backCallback != null) {
                    backCallback.onBackFinish();
                    return;
                }
                if (!isNeedBanBack()) {
                    finish();
                } else {
                    CWLog.d("banBack", "禁止返回");
                }
            }
        });


    }

    @Override
    public void loadData() {
        if (mReceiveWebPath == null) {
            mWebView.loadData("空", "text/html", "utf-8");
        } else {

            String urlHead = "http://";
            String urlHeads = "https://";
            String urlHeadfile = "file://";
            if (!mReceiveWebPath.startsWith(urlHead)
                    && !mReceiveWebPath.startsWith(urlHeads)
                    && !mReceiveWebPath.startsWith(urlHeadfile)) {
                mHandlerWebUrl = urlHead + mReceiveWebPath;
            }
            setTitleText(mFirstTitle);
        }

        mWebView.loadUrl(mHandlerWebUrl);
        if (NetworkUtils.isOnline()) {

        } else {
            rel_pay_container.setVisibility(View.GONE);
            rel_no_net_work.setVisibility(View.VISIBLE);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage)
                return;
            Uri result = intent == null || resultCode != RESULT_OK ? null
                    : intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        }
    }


    /**
     * 传值key
     *
     * @author RES-KUNZHU
     */
    public class IntentString {
        /**
         * 跳转类型
         */
        public static final String INTENT_STRING_TYPE = "INTENT_STRING_TYPE";

        /**
         * 标题
         */
        public static final String INTENT_STRING_TITLE = "INTENT_STRING_TITLE";

        /**
         * url
         */
        public static final String INTENT_STRING_URL = "INTENT_STRING_URL";

    }

    /**
     * 检查手机是否安装了Flash
     *
     * @return
     */
    private boolean isInstalledFlash() {
        PackageManager pm = getPackageManager();
        List<PackageInfo> infoList = pm
                .getInstalledPackages(PackageManager.GET_SERVICES);
        for (PackageInfo info : infoList) {
            if ("com.adobe.flashplayer".equals(info.packageName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 未安装Flash
     */
    private void uninstallFlash() {
        // Javascript添加Java本地对象方法回调
        mWebView.addJavascriptInterface(new AndroidBridge(), "android");
        // 加载一个本地的网页提示用户
        mWebView.loadUrl("file:///android_asset/uninstalledFlash.html");
    }

    /**
     * android 桥
     *
     * @author res-jxliu
     */
    private class AndroidBridge {
        @JavascriptInterface
        public void goMarket() {
            mBackHandler.post(new Runnable() {
                public void run() {

                    if (isFinishing()) {
                        return;
                    }

                    BaseJumpManager.jumpToSysBrowser(BrowserActivity.this, Uri.parse(mUrl));

                    finish();
                }
            });
        }
    }

    /**
     * js弹出框
     *
     * @param view         webview
     * @param url          地址
     * @param message      消息实体
     * @param defaultValue 默认值
     * @param result       结果
     */
    private void jsPrompt(WebView view, String url, String message,
                          String defaultValue, final JsPromptResult result) {
        try {
            if (!isFinishing()) {
                CWDialog dialog = new CWDialog(view.getContext(), false, false);
                dialog.setTitle(R.string.tips);
                dialog.setTitleTextColor(Color.BLACK);
                dialog.setMessage(message,
                        (int) getResources()
                                .getDimension(R.dimen.text_size_default),
                        Color.BLACK);
                dialog.setPositiveButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                result.confirm();
                            }
                        });
                dialog.setNegativeButton(android.R.string.cancel,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                result.cancel();
                            }
                        });
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * webview弹出确认框
     *
     * @param view    webview
     * @param url     地址
     * @param message 消息实体
     * @param result  结果
     */
    private void jsConfirm(WebView view, String url, String message,
                           final JsResult result) {
        try {
            if (!isFinishing()) {
                CWDialog dialog = new CWDialog(view.getContext(), false, false);
                dialog.setTitle(R.string.tips);
                dialog.setTitleTextColor(Color.BLACK);
                dialog.setMessage(message,
                        (int) getResources()
                                .getDimension(R.dimen.text_size_default),
                        Color.BLACK);
                dialog.setPositiveButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                result.confirm();
                            }
                        });
                dialog.setNegativeButton(android.R.string.cancel,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                result.cancel();
                            }
                        });
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void jsAlert(WebView view, String url, String message,
                         final JsResult result) {
        try {
            CWDialog dialog = new CWDialog(view.getContext(), false, false);
            dialog.setTitle(R.string.tips);
            dialog.setTitleTextColor(Color.BLACK);
            dialog.setMessage("\n" + message + "\n",
                    (int) getResources()
                            .getDimension(R.dimen.text_size_default),
                    Color.BLACK);
            dialog.setPositiveButton(android.R.string.ok,
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            result.confirm();
                        }
                    });
            dialog.setNegativeButton(android.R.string.cancel,
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            result.cancel();
                        }
                    });
            if (dialog != null && !dialog.isShowing()) {
                dialog.show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 网络路径
     *
     * @return 路径
     */
    public String getPath() {
        return mReceiveWebPath;
    }

    /**
     * 设置路径
     *
     * @param path
     */
    public void setPath(String path) {
        this.mHandlerWebUrl = this.mReceiveWebPath = path;
    }

    public void setTitle(String title) {
        this.mFirstTitle = title;
    }

    @Override
    public void preCreate() {
        Intent in = getIntent();
        if (in != null) {
            mReceiveWebPath = in.getStringExtra(IntentString.INTENT_STRING_URL);
            mHandlerWebUrl = mReceiveWebPath;
            mFirstTitle = in.getStringExtra(IntentString.INTENT_STRING_TITLE);
            jumpType = getIntent().getIntExtra(IntentString.INTENT_STRING_TYPE,
                    BrowerJumpType.TYPE_ASSEY);
        }
    }

    public WebView getmWebView() {
        return mWebView;
    }

    public void setmWebView(WebView mWebView) {
        this.mWebView = mWebView;
    }

    private static class LongTask extends AsyncTask<Void, Integer, Void> {

        private int progress = mProgress == null ? 0 : mProgress.getProgress();

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (mProgress != null)
                mProgress.setVisibility(View.VISIBLE);
        }

        @Override
        protected Void doInBackground(Void... params) {
            while (progress <= mNewProgress) {
                progress++;
                try {
                    if (mNewProgress == 100) {
                        Thread.sleep(5);
                    } else {
                        Thread.sleep(20);
                    }
                    publishProgress(progress);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            if (values == null || values.length == 0) {
                return;
            }
            int p = values[0];
            if (mProgress != null) {
                mProgress.setProgress(p);
            }
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            if (mNewProgress == 100 && mProgress != null) {
                mProgress.setVisibility(View.GONE);
            }
        }

    }

}
